package cn.dm.service.impl;

import cn.dm.client.RestDmUserClient;
import cn.dm.common.*;
import cn.dm.pojo.DmUser;
import cn.dm.service.LocalUserService;
import cn.dm.service.SmsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class LocalUserServiceImpl implements LocalUserService {

    @Resource
    private RestDmUserClient restDmUserClient;
    @Resource
    private SmsService smsService;
    @Resource
    private RedisUtils redisUtils;

    /**
     * 根据条件查询用户信息(手机号或邮箱)
     *
     * @param phone
     * @return
     * @throws Exception
     */
    @Override
    public DmUser getDmUserListByMap(String phone) throws Exception {
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("phone",phone);
        List<DmUser> list =restDmUserClient.getDmUserListByMap(map);
        if(EmptyUtils.isNotEmpty(list) && list.size()==1){
            return list.get(0);
        }
        return null;
    }

    /**
     * 手机号注册
     *
     * @param dmUser @throws Exception
     * @return
     */
    @Override
    public boolean registerUserByPhone(DmUser dmUser) throws Exception {
        String phone=dmUser.getPhone();
        //1.生成短信验证码
        String code=String.valueOf(MD5.getRandomCode());
        //2.发送短信验证码
        //datas测试的时间
        String[] datas={code,"100"};
        smsService.sendSmsMessage(phone,"1",datas);
        //3.将短信验证码存入Redis中
        String key  ="active:"+phone;
        redisUtils.set(key,6000,code);
        return true;
    }

    /**
     * 根据短信验证码注册用户
     *
     * @param dmUser
     * @param vscode
     * @return
     * @throws Exception
     */
    @Override
    public int userRegistration(DmUser dmUser, String vscode) throws Exception {
        //1:读取Rides中存取的（手机短信验证码/邮箱激活码）
        String key = "active:"+dmUser.getPhone();
        log.info("K值："+key);
        String redisCode = (String) redisUtils.get(key);
        log.info("V值："+redisCode);
        //2:判断是否读取到（手机短信验证码/邮箱激活码）
        if(EmptyUtils.isNotEmpty(redisCode)){
            //读取成功，判断用户输入的（手机短信验证码/邮箱激活码）是否和Redis中的一致
            if(redisCode.equals(vscode)){
                String password = MD5.getMd5(dmUser.getPassword(), 32);
                dmUser.setPassword(password);
                dmUser.setCreatedTime(new Date());
                Integer i = restDmUserClient.qdtxAddDmUser(dmUser);
                if(i!=0){
                    return 1;
                }
            }else {
                return -1;
            }
        }
        return 0;
    }

    @Override
    public DmUser findUserWeiXinById(String openId) throws Exception {
        return restDmUserClient.findByWxUserId(openId);
    }

    @Override
    public Long createUser(DmUser user) throws Exception {
        return restDmUserClient.createDmUser(user);
    }
}
